import Singleton from '../Base/Singleton'

interface IItem {
  func: Function,
  ctx: unknown
}

export default class EventManage extends Singleton {

  static get Instance() {
    return super.GetInstance<EventManage>()
  }
  private eventDir: Map<string, Array<IItem>> = new Map()
  // 绑定事件
  on(eventName: string, func: Function, ctx: unknown) {
    if (this.eventDir.has(eventName)) {
      this.eventDir.get(eventName).push({func, ctx})
    }else {
      this.eventDir.set(eventName, [{func, ctx}])
    }
  }
  off(eventName: string, func: Function){
    if (this.eventDir.has(eventName)) {
      let index = this.eventDir.get(eventName).findIndex(i => i.func === func)
      index > -1 && this.eventDir.get(eventName).splice(index, 1)
    }
  }
  emit(eventName: string, ...args: unknown[]){
    if (this.eventDir.has(eventName)) {
      this.eventDir.get(eventName).forEach(({func, ctx}) => {
        ctx ?func.apply(ctx, args) : func(...args)
      })
    }
  }
  clear() {
    this.eventDir.clear()
  }
}
